<?php
namespace Duobao\Controller;

use Com\Sms\Sms as Sms;
use Duobao\Controller\LogController as MyLog;
use Duobao\Model\DBConfModel as DBConf;

class CommonController extends ControllerBase{

    /**
     * 默认
     */
    public function index()
    {
        echo "<!--hi , i'm from " . MODULE_NAME . "~" . APP_STATUS, "-->";
    }

    /**
     * 图片上传功能,未使用
     */
    public function uploadImg(){
        return '图片上传路径';
    }


    /**
     * 通过ip获取用户地址，未使用
     */
    function getAddressByIP($ip){
        $ch = curl_init();
        $url = C('BAIDUAPI').$ip;
        $header = array(
            "apikey: ".C('BAIDUAPI_KEY'),
        );
        // 添加apikey到header
        curl_setopt($ch, CURLOPT_HTTPHEADER  , $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // 执行HTTP请求
        curl_setopt($ch , CURLOPT_URL , $url);
        $res = curl_exec($ch);

        $res = json_decode($res,true);

        return $res['data']['province'].$res['data']['city'];
    }

    /**
     * 发送短信接口
     */
    public function sendSMS(){
        $ret = array();
        $ret['status'] = 200;
        $ret['msg'] = '';
        $ret['data'] = array();

        try{
            #验证token，以及用户的手机号
            $uid = $this->getUid(I('get.token'));
            $phone = I('post.phone');
            $isMob="/^1[3-5,7,8]{1}[0-9]{9}$/";
            if(!preg_match($isMob,$phone)){
                E('手机号码格式错误',403);
            }else{
                if(!is_numeric($uid)){
                    E('token 失效',500);
                }


                #对ip进行限制，上的同一个id,1个小时能发送5次
                $model = M('message');
                $ip = $_SERVER['REMOTE_ADDR'];
                $count = $model->query("select count(*) as mycount from __PREFIX__message WHERE `ip` ='$ip' and `uid` = ".$uid." and time > ".(time()-3600));

                if($count[0]['mycount'] > C('SMS_LIMIT')){
                    E('同一个ip上的同一用户1小时内发送短信超过5次',403);
                }else{
                    #发送验证码，并记录结果到数据库
                    $checkCode = rand(100000,999999)."|".time();
                    $member = M('member');
                    $condition['uid'] = $uid;
                    $code['mobilecode'] = $checkCode;
                    $member->where($condition)->save($code);
                    $messageStr = '您在'.C("APP_NAME").'的验证码：'.explode('|',$checkCode)[0].'，5分钟内有效。如非本人操作，可不理会！';

                    $sms = new Sms();
                    $result = $sms->sendSMS($phone,$messageStr);
                    #验证发送的结果
                    $result = explode(',',$result);
                    if($result[1] == 0){
                        #记录发送日志到数据表中

                        $data['ip'] = $_SERVER['REMOTE_ADDR'];
                        $data['phone'] = $phone;
                        $data['time'] = strtotime($result[0]);
                        $data['content'] = $messageStr;
                        $data['uid'] = intval($uid);#写入uid
                        $dbResult = $model ->add($data);
                        #判断数据库的是否录入
                        if(!$dbResult){
                            MyLog::write('短信的记录日志错误');
                        }

                        $ret['data']['status'] = true;#返回true表示发送成功
                    }else{
                        $result['data']['status'] = false;#返回false，表示发送失败
                        #记录发送日志
                        MyLog::write($result);
                    }
                }
            }
        }catch (\Exception $e){
            $ret['status'] = $e->getCode();
            $ret['msg'] = $e->getMessage();
        }

        return $this->response($ret);
    }

    /**
     * 验证用户的号码与手机号
     * 用户输入手机验证码后的手机验证
     */
    public function verifyPhone(){
        $ret = array();
        $ret['status'] = 200;
        $ret['msg'] = '';
        $ret['data'] = array();

        try{
            #获取用户输入的验证码，手机
            $uid = $this->getUid(I('get.token'));
            #$phone = I('post.phone');考虑不需要再次传递phone
            $code = I('post.code');

            #验证输入信息的合法性
            if( empty($code) || !is_numeric($uid)){
                $ret['status'] = 403;
                $ret['msg'] = 'empty of phone or verify or token is invalid';
            }else{
                $condition['uid'] = $uid;
                #数据库获取发送验证码是的用户的手机
                $messageModel = M('message');
                $phone = $messageModel->where($condition)->order('time desc')->limit(1)->getField('phone');

                #获取用户表里面的发送验证码时候的记录
                $member = M('member');
                $dbcode = $member->where($condition)->getField('mobilecode');
                $dbcode = explode('|',$dbcode);
                #判断验证码是否失效，和验证码的正确性,更新用户数据表
                if($dbcode[0] == $code && time()-$dbcode[1] < 300){
                        $data['mobilecode'] = 1;
                        $data['mobile'] = $phone;
                        $result = $member->where($condition)->save($data);

                        #判断数据库的更新是否成功
                        if($result){
                            $ret['data']['status'] = true;
                            $ret['data']['msg'] = '';
                        }else{
                            $ret['data']['status'] = false;
                            $ret['data']['msg'] = '数据库更新失败';
                        }
                }else{
                    $ret['status'] = false;
                    $ret['msg'] = 'verify code is error or out of time';
                }
            }
        }catch (\Exception $e){
            $ret['status'] = $e->getCode();
            $ret['msg'] = $e->getMessage();
        }

        return $this->response($ret);
    }

    #返回
    public function shareInterface(){
        $ret = array();
        $ret['status'] = 200;
        $ret['msg'] = '';
        $ret['data'] = array();

        try{
            $dbconf = new DBConf();
            #获取配置文件中的分享标题和分享描述
            $share_title = $dbconf->getConfField('wx_share_title');
            $share_desc = $dbconf->getConfField('wx_share_desc');
            $share_img = $dbconf->getConfField('wx_share_img');

            #判断如果没有，配置显示默认
            if($share_img){
                $ret['data']['shareImg'] = $share_img;
            }else{
                $ret['data']['shareImg'] = 'http://t2.qpic.cn/mblogpic/acbe186cebda1d1e893a/80';
            }
            if($share_desc){
                $ret['data']['shareName'] = $share_desc;
            }else{
                $ret['data']['shareName'] = '一元云购';
            }

            if($share_title){
                $ret['data']['shareTitle'] = $share_title;
            }else{
                $ret['data']['shareTitle'] = '一元云购';
            }
        }catch (\Exception $e){
            $ret['msg'] = $e->getMessage();
            $ret['status'] = $e->getCode();
        }

        return $this->response($ret);
    }

    /* end of Common controller */
}